package com.vislardo.app.notebook.view;

import com.vislardo.app.notebook.model.NoteInfo;
import com.vislardo.app.notebook.utils.DataManager;
import com.vislardo.app.notebook.utils.NoteFileManager;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginView extends JFrame {

    //口令输入框
    private JTextField codeField;
    //打开日记本按钮
    private JButton openNoteButton;
    //创建日记本按钮
    private JButton  startNoteButton;


    public LoginView(){
        setTitle("私密日记本");
        setSize(300,140);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        add(panel);
        placeComponents(panel);
        setVisible(true);
    }


    private void placeComponents(JPanel panel){
        panel.setLayout(null);

        JLabel codeLabel = new JLabel("输入口令");
        codeLabel.setBounds(20,20,80,25);
        panel.add(codeLabel);

        codeField = new JTextField(20);
        codeField.setBounds(100, 20, 165, 25);
        panel.add(codeField);

        openNoteButton = new JButton("打开");
        openNoteButton.setBounds(20, 55, 80, 25);
        panel.add(openNoteButton);

        startNoteButton = new JButton("创建");
        startNoteButton.setBounds(170, 55, 80, 25);
        panel.add(startNoteButton);

        openNoteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String code = codeField.getText();
                NoteInfo info = DataManager.getInstance().getNoteInfo(code);
                if(info !=null){
                    JOptionPane.showMessageDialog(null,"登录成功");
                    new MainView(info);
                    dispose();
                }else{
                    JOptionPane.showMessageDialog(null,"口令输入错误");
                }
            }
        });


        startNoteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String code = codeField.getText();
                NoteInfo info = DataManager.getInstance().getNoteInfo(code);
                if(info !=null){
                    JOptionPane.showMessageDialog(null,"当前日记本已存在，直接打开");
                    new MainView(info);
                    dispose();
                }else{
//                    NoteInfo info_new = DataManager.getInstance().createNewNote(code);
                    NoteInfo info_new = NoteFileManager.getInstance().createNewNote(code);

                    DataManager.getInstance().saveNewBookInfo(info_new);

                    JOptionPane.showMessageDialog(null,"创建新日本直接打开");
                    new MainView(info_new);
                    dispose();
                }
            }
        });
    }
}
